//
//  Near_View.m
//  K-Music
//
//  Created by CHUN on 16/3/6.
//  Copyright © 2016年 CHUN. All rights reserved.
//

#import "Near_View.h"
#import "Chat_Mode.h"
#import "Search_ChatVC.h"
#import "Friends_see.h"

@implementation Near_View

-(id)initWithFrame:(CGRect)frame superViewCtr:(UIViewController *)superCtr{
    
    self = [super initWithFrame:frame];
    if(self){
        _superViewCtr = superCtr;
        
        _Near_TableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) style:(UITableViewStylePlain)];
        _Near_TableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _Near_TableView.allowsSelection = YES;
        _Near_TableView.delegate = self;
        _Near_TableView.dataSource = self;
        _Near_TableView.backgroundColor = RGB(255, 255, 255);
        
        [self addSubview:_Near_TableView];
        
        [self get_chat_group];
        
    }
    return self;
}



- (void)get_chat_group
{
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString*infoStr11=[NSString stringWithFormat:@"/api/chat_group?page=0&size=20&sort=createdDate,DESC"];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:infoStr11];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    //    创建请求
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        
        NSLog(@"成功GET --> %@", dic);
        if ( [dic[@"errorCode"]intValue] != 1404 )
        {
            NSArray*content=dic[@"body"][@"content"];
            
            _chatData=[NSMutableArray array];
            
            for (NSDictionary * Data in content) {
                Chat_Mode * mode =[[Chat_Mode alloc]init];
                
                mode.address =Data[@"address"];
                mode.aid =Data[@"id"];
                mode.createdBy =Data[@"createdBy"];
                mode.createdDate =Data[@"createdDate"];
                mode.descriptionX =Data[@"description"];
                mode.lastModifiedBy =Data[@"lastModifiedBy"];
                mode.lastModifiedDate =Data[@"lastModifiedDate"];
                
                mode.latitude =Data[@"latitude"];
                mode.longitude =Data[@"longitude"];
                
                mode.level =Data[@"level"];
                mode.name =Data[@"name"];
                mode.pictureUrl =Data[@"pictureUrl"];
                mode.tag =Data[@"tag"];
                
                [mode fixedString];
                
                [_chatData addObject:mode];
                
            }
            [_Near_TableView reloadData];
        }
        else{
            _chatData = nil;
            [_Near_TableView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        
        [MBProgressHUD showErrorWithStatus:@"个人信息获取失败" toView:self];
        
    }];
}

#pragma mark ------- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return WIDTH/4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _chatData.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 120;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH,130)];
    headerview.backgroundColor = [UIColor whiteColor];
    
    UIImageView * HeaderView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    UIImageView * View = [[UIImageView alloc]initWithFrame:CGRectMake(25, 10, WIDTH-50, 30)];
    HeaderView.backgroundColor = RGB(255, 255, 255);
    View.image = [UIImage imageNamed:@"search_icon3"];
    
    HeaderView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer * PersonalTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(search)];
    
    [HeaderView addGestureRecognizer:PersonalTap];
    
    [HeaderView addSubview:View];
    
    [headerview addSubview:HeaderView];
    
    
    NSArray*textData;
    
    textData=[NSArray arrayWithObjects:@"周杰伦",@"罗志祥",@"蔡依林",@"刘德华",@"SHE",@"邓超",@"五月天",@"更多",nil];
    
    for (int j = 0 ; j<2 ; j++) {
        
        for (int i=0; i< 4; i++) {
            int a = j*4;
            UIButton*topBtn=[[UIButton alloc]initWithFrame:CGRectMake(i*WIDTH/4, j*40+50,WIDTH/4, 40)];
            topBtn.backgroundColor=[UIColor whiteColor];
            //边框宽度
            [topBtn.layer setBorderWidth:1.0];
            topBtn.layer.borderColor=RGB(241, 241, 241).CGColor;
            [topBtn setTitle:textData[i+a] forState:UIControlStateNormal];
            [topBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [topBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
            
            topBtn.userInteractionEnabled = YES;
            topBtn.tag=1000+i+a;
            [topBtn addTarget:self action:@selector(TopButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [headerview addSubview:topBtn];
        }
    }
    return headerview;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellID = @"cellID";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    // 先清空cell.contentView中的子view
    for (UIView * subview in cell.contentView.subviews)
    {
        [subview removeFromSuperview];
    }
    
    Chat_Mode * mode = [[Chat_Mode alloc]init];
    mode =_chatData[indexPath.row];
    
    // 图片
    UIImageView *iconView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, WIDTH/4-20, WIDTH/4-20)];
    iconView.layer.cornerRadius = iconView.bounds.size.width * 0.5;
    iconView.layer.masksToBounds =YES;
    [iconView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",mode.pictureUrl]]];
    
    iconView.userInteractionEnabled = YES;
    UITapGestureRecognizer * PersonalTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(Meassage_Pic)];
    [iconView addGestureRecognizer:PersonalTap];
    [cell.contentView addSubview:iconView];
    
    //标题
    UILabel * nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconView.frame)+20, 10 , WIDTH/2,30)];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    nameLabel.text = mode.name;
    nameLabel.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:nameLabel];
    
    UILabel * timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconView.frame)+20, CGRectGetMaxY(nameLabel.frame), WIDTH*0.5 ,30)];
    timeLabel.textAlignment = NSTextAlignmentLeft;
    //timeLabel.text = @"09/2  19:00";
    timeLabel.text = mode.createdDate;
    timeLabel.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:timeLabel];
    
    UILabel *  addres_Lable = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(timeLabel.frame)+20, CGRectGetMaxY(nameLabel.frame) , WIDTH*0.3, 30)];
    addres_Lable.textAlignment = NSTextAlignmentLeft;
    addres_Lable.text = mode.address;
    addres_Lable.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:addres_Lable];
    
    //正文
    UILabel *  contentLable = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconView.frame)+20, CGRectGetMaxY(timeLabel.frame) , WIDTH*0.7, 30)];
    contentLable.textAlignment = NSTextAlignmentLeft;
    contentLable.text = mode.tag;
    contentLable.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:contentLable];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:tableView.indexPathForSelectedRow animated:YES];
}

- (void)Meassage_Pic
{
    NSLog(@"Meassage_Pic");
    
    
}

-(void)TopButtonClick:(UIButton*)btn{
    
    NSLog(@"%ld",(long)btn.tag);
    
    Search_ChatVC * chat = [[Search_ChatVC alloc]init];
    
    chat.navigationItem.title = [NSString stringWithFormat:@"%@", btn.titleLabel.text];
    
    [_superViewCtr.navigationController pushViewController:chat animated:YES];
//
//    [self.navigationController pushViewController:chat animated:NO];
    
}

- (void)search
{
    
    Friends_see * see = [[Friends_see alloc]init];
    see.navigationItem.title = @"搜索群组";
    
    [_superViewCtr.navigationController pushViewController:see animated:YES];

    //    [MBProgressHUD showErrorWithStatus:@"搜索" toView:self.view];
    
}




@end
